package com.example.beryl.Util;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.example.beryl.R;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 接口公共类
 */
public class HandlePublic {
    private getResult getResult;

    public void setGetResult(getResult getResult1)
    {
        this.getResult = getResult1;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            try {
                //NormalProgressDialog.stopLoading();
                getResult.getCode(msg.what,msg.obj);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }
    };


    //回调接口
    public interface getResult
    {
        void getCode(int what,Object t) throws JSONException;
    }

//    public void startLoad(Context context)
//    {
//        NormalProgressDialog.showLoading(context);
//    }


    //把结果放进handler
    public void setmHandler(int what,Object msg)
    {
        Looper.prepare();
        Message message=new Message();
        message.what = what;
        message.obj = msg;
        mHandler.sendMessage(message);
        Looper.loop();
    }

    public void Alert(String Message, Context context)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("信息:");
        builder.setMessage(Message);
        builder.setNegativeButton("确定",
                (dialog, which) -> dialog.dismiss());
        builder.create().show();
    }


    /**
     * json格式转换20230810
     * @param json
     * @return
     */
    public String JosnChange(String json)
    {
        String result = "";
        if (json.substring(0,1).equals("["))
        {
            json = json.replace("[","");
            json = json.replace("]","");
            result = json;
            return result;
        }
        if (json.substring(0,1).equals("{"))
        {
            json = "[" + json + "]";
            result = json;
        }
        return result;
    }

    public List<HashMap<String,String>> listChacge(List<HashMap<String,String>> list)
    {
        List<HashMap<String,String>> mapList = new ArrayList<>();
        for (int i = 1; i<list.size();i++)
        {
            mapList.add(list.get(i));
        }
        return mapList;
    }

    /**
     * 获取当前日期
     * @param i 1为- 2 为/
     * @return
     */
    public String Date(int i)
    {
        Date date = new Date();
        SimpleDateFormat dateFormat = null;
        if (i == 1)
        {
            dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        }
        if (i == 2)
        {
            dateFormat= new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        }
        String rt = dateFormat.format(date);
        return rt;
    }

    /**
     * 提交数据时组成json
     * @param hashMap
     * @return
     */
    public String MakeJson(HashMap<String,String> hashMap)
    {
        String json;
        try
        {
            Gson gson = new Gson();
            json = gson.toJson(hashMap);
            json = JosnChange(json);
        }catch (RuntimeException e)
        {
            return e.getMessage();
        }
        return json;
    }

    public String ChangeString(String para)
    {
        try
        {
            if (para.contains("[") || para.contains("{")) {
                para = para.replace('[',' ');
                para = para.replace(']',' ');
                para = para.trim();
            }
        }catch (Exception e)
        {
            return e.getMessage();
        }
        return para;
    }

    /**
     * 返回实体类Json
     */
    public Object getEntity(String json, Class clazz){
        Gson gson = new Gson();
        Object object = gson.fromJson(json,clazz);
        return object;
    }

    /**
     * String 转jsonArray
     * @param json
     * @return
     * @throws JSONException
     */
    public JSONArray getJsonArray(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        return jsonArray;
    }

    public String dealDataBase(List<String> list)
    {
        String ret = null;
        try
        {
            if (list.size() > 1)
            {
                throw new Exception("返回数据异常");
            }else
            {
                ret = list.get(0);
            }
        }catch (Exception e)
        {
            ret = e.getMessage();
        }
        return ret;
    }

    //判断字符串是否含有数字
    public static boolean isNumericZidai(String str) {
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    //模拟点击
//    public void Touch()
//    {
//        long downTime = SystemClock.uptimeMillis();
//        long eventTime = SystemClock.uptimeMillis()+100;
//        float upX = binding.tiaoban.getX()+50;
//        float upY = binding.tiaoban.getY()+50;
//        MotionEvent obtainDown = MotionEvent.obtain(downTime, eventTime, ACTION_DOWN, upX, upY, 0);
//
//        long downTime1 = SystemClock.uptimeMillis();
//        long eventTime1 = SystemClock.uptimeMillis()+100;
//        float upX1 = binding.tiaoban.getX()+50;
//        float upY1 = binding.tiaoban.getY()+50;
//        MotionEvent obtainUp = MotionEvent.obtain(downTime1, eventTime1, MotionEvent.ACTION_UP, upX1, upY1, 0);
//        binding.tiaoban.dispatchTouchEvent(obtainDown);
//        binding.tiaoban.dispatchTouchEvent(obtainUp);
//        obtainDown.recycle();
//        obtainUp.recycle();
//        Log.v("wz","downTime:"+downTime+" ,eventTime:"+eventTime+" ,upX:"+upX+" ,upY:"+upY+" ,downTime1:"+downTime1+" ,eventTime1:"+eventTime1+" ,upX1:"+upX1+" ,upY1:"+upY1);
//    }


   //取消EditView 焦点
    public void getT(View v,Context context)
    {
         //= context.getCurrentFocus();
        if (isShouldHideKeyboard(v)) {
            hideKeyboard(v.getWindowToken(),context);
            v.clearFocus();
        }
    }
    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v ) {
        //如果目前得到焦点的这个view是editText的话进行判断点击的位置
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return true;
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false;
    }
    private void hideKeyboard(IBinder token,Context context) {
        if (token != null) {
            //这里先获取InputMethodManager再调用他的方法来关闭软键盘
            //InputMethodManager就是一个管理窗口输入的manager
            InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //获取mac地址
    public String get() {
        HashMap<String,String> hashMap = new HashMap<>();
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            // 遍历所有网络接口
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                // 获取MAC地址
                byte[] macBytes = networkInterface.getHardwareAddress();
                if (macBytes != null) {
                    StringBuilder macBuilder = new StringBuilder();
                    for (int i = 0; i < macBytes.length; i++) {
                        macBuilder.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? "-" : ""));
                    }
                    hashMap.put(networkInterface.getName(),macBuilder.toString());
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        String value = hashMap.get("wlan0");
        return value;
    }


    /**
     * 弹出其他Activity公共方法
     * 20231107
     */
    public void AlterDialog(Context context,JSONArray jsonret) throws JSONException {
        final Dialog dialog = new Dialog(context);
        dialog.setContentView(R.layout.activity_pmselect);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(false);//点击空白不消失
        dialog.setCancelable(false);//返回键不消失
        dialogWindow.setAttributes(lp);
        dialog.show();
        LinearLayout linearLayout = dialog.findViewById(R.id.lin);
        List<Button> objectList = new ArrayList<>(); // 创建对象列表
        Button[] o = new Button[jsonret.length()];
        for (int f = 0;f< jsonret.length();f++)
        {
            o[f] = new Button(context);
            objectList.add(o[f]);
        }
        //增加button
        for (int j = 0;j< objectList.size();j++)
        {
            String PeopleNum = jsonret.getJSONObject(j).get("cPsn_Num").toString();
            String PeoPle = jsonret.getJSONObject(j).get("cPsn_Name").toString();
            objectList.get(j).setText(PeoPle + ":" + PeopleNum);//设置按钮显示内容
            linearLayout.addView(objectList.get(j));
        }
        //设置标签，获取用户点击的按钮
        for (int i = 0;i< o.length;i++)
        {
            o[i].setTag(i);
            o[i].setOnClickListener(v -> {
                int i1 = (Integer) v.getTag();//获取点击的按钮
                try {
                    getPerson(jsonret.getJSONObject(i1).toString());
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                dialog.dismiss();
            });
        }
    }

    /**
     * 多个Person选择接口
     */
    private getPersonInter PersonGet;
    public void setGetPersonRet(getPersonInter PersonGet1)
    {
        this.PersonGet = PersonGet1;
    }
    private void getPerson(String para)
    {
        PersonGet.getPersonIn(para);
    }
    public interface getPersonInter
    {
        void getPersonIn(String ret);
    }
    /**
     *文件写入
     */
    public static String txtPath = "";
    public static void inseryt(String IpGateWay,String Name,String FlodName) throws IOException {
        String fileName = Name+ ".log";
        StringBuffer sb = new StringBuffer();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +FlodName + "/";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            txtPath = path + fileName;
            sb.append(IpGateWay);
            FileOutputStream fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
        }
    }

    /**
     * 文件读取
     * @return
     */
    public static String readLogFile(String foldName,String Name) {
        StringBuilder log = new StringBuilder();
        try {
            FileInputStream fis = new FileInputStream("/storage/emulated/0/" + foldName + "/" + Name + ".log");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            String line;
            while ((line = br.readLine()) != null) {
                log.append(line);
            }
            br.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return log.toString();
    }

    /**
     * ping 网络
     */
    public static Boolean ping(String host) {
        try {
            Process process = Runtime.getRuntime().exec("ping -c 4 -w 3 " + host);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            int connectedCount = 0;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                connectedCount += getCheckResult(line);
                if (connectedCount > 0)
                {
                    break;
                }
            }
            reader.close();
            process.waitFor();
            if (connectedCount == 0)
            {
                return false;
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取网络状态
     * @param line
     * @return
     */
    private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
        Pattern pattern = Pattern.compile("(TTL=\\d+)",  Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
}
